package com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;

public class HttpParser {
	public static String replaceAll(String str, String pattern, String replace) {
		int s = 0;
		int e = 0;

		StringBuffer result = new StringBuffer();
		while ((e = str.indexOf(pattern, s)) >= 0) {
			result.append(str.substring(s, e));
			result.append(replace);
			s = e + pattern.length();
		}
		result.append(str.substring(s));
		return result.toString();

	}

	static public Request parse(Socket s, String root) throws IOException {
		ArrayList<String[]> arrayListForMeThod = new ArrayList<String[]>();
		String query1;
		String path;
		String requestCookie = null;
		String progRequest = null;
		String classpath = null;

		Request parsedRequest = new Request(null, null, null, s, null);
		BufferedReader in = new BufferedReader(new InputStreamReader(
				s.getInputStream()));

		path = null;
		while ((query1 = in.readLine()) != null) {
			if (query1.isEmpty()) {
				break;
			}
			System.out.println(query1);
			String[] divideQuery1 = query1.split(" ");
			if (divideQuery1[0].equals("Cookie:")) {
				requestCookie = query1;
			}
			arrayListForMeThod.add(divideQuery1);
		}
		if ((arrayListForMeThod.get(0)[0].equals("GET"))
				|| (arrayListForMeThod.get(0)[0].equals("POST"))) {
			path = replaceAll(arrayListForMeThod.get(0)[1], "/", "\\");
			
			    String[] programingRequest = path.split("\\?");
				
				path = root + programingRequest[0];
				if (programingRequest.length>1){
				classpath = programingRequest[1];
				progRequest = programingRequest[2];
				}
			
			
				path = root +path;

			

			if (path.equals(root + "\\")) {
				path += "index.html";
			}

			path = replaceAll(path, " ", "");
			if (path.indexOf(".html") > 0) {
				String[] tmp = path.split(".html");
				path = tmp[0] + ".html";
			}

			Integer idSession = Cookie.getCookie(requestCookie).get(
					"jidsession");
			SessionCollection sessionCol = SessionCollection.Instance();
			Session session = sessionCol.getSession(idSession);
			sessionCol.updateSession(session);

			Request parsedRequest1 = new Request(arrayListForMeThod.get(0)[0],
					path, arrayListForMeThod.get(0)[2], s, session.getId());

			parsedRequest = parsedRequest1;
			parsedRequest.setProgRequest(progRequest);
			parsedRequest.setClasspath(classpath);
			
		}
		return parsedRequest;

	}

}
